$(document).ready(function () {
    // bootstrap tooltip初始化
    $('[data-toggle="tooltip"]').tooltip();

    // 项目表格实例化
    let table_project_list = new getProjectListTable();
    table_project_list.init();

    // 绑定事件
    $btn_add_project.on('click', function(){
        $modal_add_project.modal('show');
    });
    $radio_email_notify_yes.on('click', function () {
        $div_email_notify_more_config.collapse('show');
    });
    $radio_email_notify_no.on('click', function () {
        $div_email_notify_more_config.collapse('hide');
    });

    $btn_save_add_project.on('click', addProject);
    $btn_save_modify_project.on('click', modifyProject);
    $btn_save_config_project.on('click', updateConfigProject)
    $btn_test_crontab.on('click', testCrontab)

});

let $table_project_list = $('#table-project-list');
let $modal_add_project = $('#modal-add-project');
let $modal_modify_project = $('#modal-modify-project');
let $modal_config_project = $('#modal-config-project');
let $btn_add_project = $('#btn-add-project');
let $input_add_project_name = $('#input-add-project-name');
let $input_add_project_description = $('#input-add-project-description');
let $input_modify_project_id = $('#input-modify-project-id');
let $input_modify_project_name = $('#input-modify-project-name');
let $input_modify_project_description = $('#input-modify-project-description');
let $input_config_project_id = $('#input-config-project-id');
let $radio_stop_on_error_yes = $('#radio-stop-on-error-yes');
let $radio_stop_on_error_no = $('#radio-stop-on-error-no');
let $radio_clear_http_cookie_yes = $('#radio-clear-http-cookie-yes');
let $radio_clear_http_cookie_no = $('#radio-clear-http-cookie-no');
let $radio_ding_talk_notify_yes = $('#radio-ding-talk-notify-yes');
let $radio_ding_talk_notify_no = $('#radio-ding-talk-notify-no');
let $radio_email_notify_yes = $('#radio-email-notify-yes');
let $radio_email_notify_no = $('#radio-email-notify-no');
let $div_email_notify_more_config = $('#email-notify-more-config');
let $radio_email_notify_when_default = $('#radio-email-notify-when-default');
let $radio_email_notify_when_failure_or_error = $('#radio-email-notify-when-failure-or-error');
let $checkbox_use_scheduler = $('#checkbox-use-scheduler');
let $input_scheduler_cron = $('#input-scheduler-cron');
let $btn_test_crontab = $('#btn-test-crontab');
let $crontab_test_success = $('.crontab.text-success');
let $crontab_test_danger = $('.crontab.text-danger');
let $btn_save_add_project = $('#btn-save-add-project');
let $btn_save_modify_project = $('#btn-save-modify-project');
let $btn_save_config_project = $('#btn-save-config-project');

function getProjectListTable() {
    let table = new Object;

    table.init = function () {
        $table_project_list.bootstrapTable({
            buttonsClass: 'primary',            // 定义按钮类
            cardView: false,                    // 是否显示详细视图
            cache: false,                       // 是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性
            // checkboxHeader: false,              // 展示check-all按钮
            classes: 'table table-bordered table-hover table-striped table-borderless',  // 图表样式
            clickToSelect: false,               // 是否启用点击选中行
            detailView: false,                  // 是否显示父子表
            // height: 500,                        // 行高，如果没有设置height属性，表格自动根据记录条数决定表格高度
            locale: 'zh-CN',
            method: 'post',                     // 请求方式
            minimumCountColumns: 2,             // 最少允许的列数
            pageNumber:1,                       // 初始化加载第一页，默认第一页
            pagination: true,                   // 是否显示分页
            pageSize: 5,                        // 每页的记录行数
            pageList: [5, 10, 25, 50, 100],     // 可供选择的每页的行数
            paginationLoop: true,               // 循环翻页模式
            // queryParams: table.queryParams,     //传递参数
            search: true,                       // 是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            // searchHighlight: true,              // bug?
            striped: true,                      // 是否显示行间隔色
            strictSearch: false,                // 严格搜索，非模糊搜素
            showColumns: true,                  // 是否显示所有的列
            showColumnsToggleAll: true,         // 全选开关
            showPaginationSwitch: true,         // 展示是否分页开关
            showRefresh: true,                  // 是否显示刷新按钮
            showToggle:true,                    // 是否显示详细视图和列表视图的切换按钮
            sidePagination: 'client',           // 分页方式：client客户端分页，server服务端分页
            // sortable: true,                     //是否启用排序
            sortClass: 'table-active',          // 排序列样式
            // sortOrder: 'asc',                   // 排序方式
            sortReset: true,                    // 重置被排序的列（点击三次）
            toolbar: '#table-project-toolbar',  // 工具按钮用哪个容器
            toolbarAlign: 'left',               // 工具栏按钮位置
            url: '/ajax/project/get',           // 请求后台的URL
            uniqueId: 'id',                     // 每一行的唯一标识，一般为主键列
            // virtualScroll: true,
            columns: [
            // {
            //     checkbox: true
            // },
            {
                field: 'id',
                title: '编号',
                class: 'cursor-pointer',
            }, {
                field: 'name',
                title: '项目名称',
                class: 'cursor-pointer',
            }, {
                field: 'description',
                title: '项目描述',
                class: 'cursor-pointer',
            }, {
                field: 'create_time',
                title: '创建时间',
                sortable: true,
                class: 'cursor-pointer',
            }, {
                field: 'last_updated_time',
                title: '最后更新时间',
                sortable: true,
                class: 'cursor-pointer',
            }, {
                filed: 'action',
                title: '操作',
                formatter: actionFormatter,
                events: 'actionEvents',
            }
            ],
            // 事件
            onClickRow: onClickRow,
        });
    };

    function actionFormatter(value, row, index, field) {
        return '<button class="btn btn-outline-secondary btn-delete-row mr-2">删除</button>' +
            '<button class="btn btn-outline-secondary btn-modify-row mr-2">修改</button>' +
            '<button class="btn btn-outline-secondary btn-config-row">设置</button>'
    }

    function onClickRow(row, $element, field){
        if (field === 5){  // 如果是点击了操作列则不跳转
            return;
        }
        window.location.href="/module?project_id=" + row.id;
    }

    window.actionEvents = {
        'click .btn-delete-row': function (event, value, row, index) {
            Swal.fire({
                title: '确定删除 ' + row.name + ' 项目吗？',
                text: "删除后将无法恢复!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                confirmButtonText: '确定',
                cancelButtonColor: '#d33',
                cancelButtonText: '取消',
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        type: 'POST',
                        url: '/ajax/project/delete',
                        data: {
                            id: row.id,
                        },
                        success: function (data, status, xhr) {
                            if (data.error_no === 0){
                                message("项目删除成功", "success");
                                $table_project_list.bootstrapTable('refresh');
                            }else{
                                message("项目删除失败: " + data.error_msg, "error");
                            }
                        },
                    });
                }
            });
        },

        'click .btn-modify-row': function (event, value, row, index) {
            $modal_modify_project.modal('show');
            $input_modify_project_id.val(row.id);
            $input_modify_project_name.val(row.name);
            $input_modify_project_description.val(row.description);
        },

        'click .btn-config-row': function (event, value, row, index) {
            $modal_config_project.modal('show');
            $crontab_test_success.text('');
            $crontab_test_danger.text('');
            $input_config_project_id.val(row.id);
            if (row.stop_on_error){
                $radio_stop_on_error_yes.prop('checked', true).parent().addClass('active');
                $radio_stop_on_error_no.prop('checked', false).parent().removeClass('active');
            }else{
                $radio_stop_on_error_yes.prop('checked', false).parent().removeClass('active');
                $radio_stop_on_error_no.prop('checked', true).parent().addClass('active');
            }
            if (row.clear_http_cookie){
                $radio_clear_http_cookie_yes.prop('checked', true).parent().addClass('active');
                $radio_clear_http_cookie_no.prop('checked', false).parent().removeClass('active');
            }else{
                $radio_clear_http_cookie_no.prop('checked', true).parent().addClass('active');
                $radio_clear_http_cookie_yes.prop('checked', false).parent().removeClass('active');
            }
            if (row.ding_talk_notify){
                $radio_ding_talk_notify_yes.prop('checked', true).parent().addClass('active');
                $radio_ding_talk_notify_no.prop('checked', false).parent().removeClass('active');
            }else{
                $radio_ding_talk_notify_yes.prop('checked', false).parent().removeClass('active');
                $radio_ding_talk_notify_no.prop('checked', true).parent().addClass('active');
            }
            if (row.email_notify){
                $radio_email_notify_yes.prop('checked', true).parent().addClass('active');
                $radio_email_notify_no.prop('checked', false).parent().removeClass('active');
                $div_email_notify_more_config.collapse('show');
            }else{
                $radio_email_notify_yes.prop('checked', false).parent().removeClass('active');
                $radio_email_notify_no.prop('checked', true).parent().addClass('active');
                $div_email_notify_more_config.collapse('hide');
            }
            if (row.email_notify_when_default){
                $radio_email_notify_when_default.prop('checked', true).parent().addClass('active');
                $radio_email_notify_when_failure_or_error.prop('checked', false).parent().removeClass('active');
            }else{
                $radio_email_notify_when_default.prop('checked', false).parent().removeClass('active');
                $radio_email_notify_when_failure_or_error.prop('checked', true).parent().addClass('active');
            }
            if (row.use_scheduler){
                $checkbox_use_scheduler.prop('checked', true);
            }else{
                $checkbox_use_scheduler.prop('checked', false);
            }
            $input_scheduler_cron.val(row.cron);
        },

    };

    return table;
}

function addProject() {
    let name = $input_add_project_name.val();
    let description = $input_add_project_description.val();

    $.ajax({
        type: 'POST',
        url: '/ajax/project/add',
        data: {
            name: name,
            description: description,
        },
        success: function (data, status, xhr) {
            if (data.error_no === 0){
                message("项目新增成功", "success");
                $modal_add_project.modal('hide');
                $table_project_list.bootstrapTable('refresh');
            }else{
                message("项目新增失败: " + data.error_msg, "error");
            }
        },
    });

}


function modifyProject() {
    let name = $input_modify_project_name.val();
    let description = $input_modify_project_description.val();
    let id = $input_modify_project_id.val();

    $.ajax({
        type: 'POST',
        url: '/ajax/project/modify',
        data: {
            id: id,
            name: name,
            description: description,
        },
        success: function (data, status, xhr) {
            if (data.error_no === 0){
                message("项目修改成功", "success");
                $modal_modify_project.modal('hide');
                $table_project_list.bootstrapTable('refresh');
            }else{
                message("项目修改失败: " + data.error_msg, "error");
            }
        },
    });

}

function updateConfigProject() {
    let id = $input_config_project_id.val();
    let cron = $input_scheduler_cron.val();
    let stop_on_error = true;
    let ding_talk_notify = false;
    let email_notify = false;
    let email_notify_when_default = false;
    let email_notify_when_failure_or_error = false;
    let clear_http_cookie = true;
    let use_scheduler = false;
    if ($radio_stop_on_error_no.is(':checked')){
        stop_on_error = false;
    }
    if ($radio_clear_http_cookie_no.is(':checked')){
        clear_http_cookie = false;
    }
    if ($radio_ding_talk_notify_yes.is(':checked')){
        ding_talk_notify = true;
    }
    if ($radio_email_notify_yes.is(':checked')){
        email_notify = true;
    }
    if ($radio_email_notify_when_default.is(':checked')){
        email_notify_when_default = true;
    }
    if ($radio_email_notify_when_failure_or_error.is(':checked')){
        email_notify_when_failure_or_error = true;
    }
    if ($checkbox_use_scheduler.is(':checked')){
        use_scheduler = true;
    }
    $.ajax({
        type: 'POST',
        url: '/ajax/project/config/modify',
        data: {
            id: id,
            stop_on_error: stop_on_error,
            ding_talk_notify: ding_talk_notify,
            email_notify: email_notify,
            email_notify_when_default: email_notify_when_default,
            email_notify_when_failure_or_error: email_notify_when_failure_or_error,
            clear_http_cookie: clear_http_cookie,
            use_scheduler: use_scheduler,
            cron: cron,
        },
        success: function (data, status, xhr) {
            if (data.error_no === 0){
                message("配置修改成功", "success");
                $table_project_list.bootstrapTable('refresh');
                $modal_config_project.modal('hide');
            }else{
                message("配置修改失败: " + data.error_msg, "error");
            }
        },
    });
}

function testCrontab() {
    let cron = $input_scheduler_cron.val();
    $crontab_test_success.text('');
    $crontab_test_danger.text('');
    $.ajax({
        type: 'POST',
        url: '/ajax/project/config/crontab/test',
        data: {
            cron: cron,
        },
        success: function (data, status, xhr) {
            if (data.error_no === 0){
                $crontab_test_success.text('最近5次执行时间为: ' + data.next_schedule_list)
            }else{
                $crontab_test_danger.text("测试失败: " + data.error_msg);
            }
        },
    });
}
